package com.ltmonitor.web.controller.command;

import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 菜单设置
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/terminalMenu")
public class TerminalMenuAction extends TerminalCommandAction {
	
	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/command/terminalMenu";
	}


	/**
	 * 
	 * @param vehicleId
	 * @param configType 0：删除终端全部信息项； 1：更新菜单； 2：追加菜单； 3：修改菜单
	 * @param inserted 菜单项目列表组成的JSON格式的字符串
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage execute(long vehicleId, int configType, String inserted) {

		Map params = super.getParams();
		try {
			JSONArray arry = JSONArray.fromObject(params.get("inserted"));
			StringBuilder errorMsg = new StringBuilder();

			int rowNo = 1;
			String menuList = "";
			if (configType > 0) {
				for (int m = 0; m < arry.size(); m++) {
					JSONObject mi = arry.getJSONObject(m);
					String ID = mi.getString("ID");
					String content = mi.getString("content");
					if (isNumeric(ID) == false)
						errorMsg.append("第一列").append(
								"第" + rowNo + "行必须为数字整数, ");
					if (StringUtil.isNullOrEmpty(content))
						errorMsg.append("第二列").append("第" + rowNo + "行不能为空, ");
					menuList += ID + "," + content + ";";
				}
				rowNo++;
			}
			if (errorMsg.length() > 0)
				return json(false, errorMsg.toString());

			TerminalCommand tc = new TerminalCommand();
			tc.setVehicleId(vehicleId);
			tc.setCmdType(JT808Constants.CMD_SET_MENU);
			tc.setCmdData(menuList);
			tc.setCmd("" + configType);
			SendCommand(tc);
			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	public static boolean isNumeric(String str) {
		if (str.matches("\\d*")) {
			return true;
		}
		return false;
	}


}
